<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>智能点餐助手</title>
    <style>
        body {
            font-family: 'PingFang SC', sans-serif;
            margin: 0;
            padding: 0;
            background: #f5f5f5;
        }
        .container {
            max-width: 480px;
            margin: 0 auto;
            padding: 20px;
            background: white;
            min-height: 100vh;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
        }
        h1 {
            font-weight: 500;
            font-size: 24px;
            margin: 16px 0 24px;
            color: #333;
            text-align: center;
        }
        .chat-container {
            height: calc(100vh - 160px);
            overflow-y: auto;
            margin-bottom: 20px;
            padding: 16px;
            border: 1px solid #ddd;
            border-radius: 8px;
            background: #fafafa;
        }
        .message {
            margin-bottom: 12px;
            padding: 8px 12px;
            border-radius: 12px;
            max-width: 80%;
            width: fit-content;
            word-wrap: break-word;
            font-size: 14px;
        }
        .user-message {
            background: #007bff;
            color: white;
            margin-left: auto;
        }
        .bot-message {
            background: #f1f1f1;
            color: #333;
            margin-right: auto;
        }
        .dish-cards-container {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            margin: 16px 0;
        }
        .dish-card {
            display: flex;
            flex-direction: column;
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            width: calc(50% - 5px);
            overflow: hidden;
        }
        .dish-image {
            width: 100%;
            height: 100px;
            object-fit: cover;
        }
        .dish-info {
            padding: 12px;
        }
        .dish-name {
            font-weight: 500;
            margin-bottom: 4px;
            color: #333;
        }
        .dish-price {
            color: #666;
            margin-bottom: 8px;
            font-size: 13px;
        }
        .add-to-cart-btn {
            background: #28a745;
            color: white;
            border: none;
            border-radius: 4px;
            padding: 6px 12px;
            cursor: pointer;
            width: 100%;
            font-size: 13px;
        }
        .add-to-cart-btn:hover {
            background: #218838;
        }
        .cart-icon {
            position: fixed;
            right: 20px;
            bottom: 20px;
            background: #007bff;
            color: white;
            width: 50px;
            height: 50px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            box-shadow: 0 2px 10px rgba(0,0,0,0.2);
        }
        .cart-icon:hover {
            background: #0069d9;
        }
        .cart-badge {
            position: absolute;
            top: -5px;
            right: -5px;
            background: red;
            color: white;
            border-radius: 50%;
            padding: 2px 6px;
            font-size: 12px;
        }
        .cart-modal {
            display: none;
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            width: 90%;
            max-width: 400px;
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.2);
            z-index: 1000;
        }
        .cart-modal.open {
            display: block;
        }
        .cart-overlay {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.5);
            z-index: 999;
        }
        .cart-overlay.open {
            display: block;
        }
        .cart-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 8px 0;
            border-bottom: 1px solid #eee;
        }
        .quantity-control {
            display: flex;
            align-items: center;
            gap: 8px;
        }
        .quantity-btn {
            width: 24px;
            height: 24px;
            border-radius: 50%;
            border: 1px solid #ddd;
            background: white;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #333;
            font-size: 16px;
            line-height: 1;
        }
        .quantity-btn:hover {
            background: #f5f5f5;
        }
        .quantity {
            min-width: 20px;
            text-align: center;
        }
        .cart-total {
            font-weight: bold;
            text-align: right;
            margin-top: 16px;
            padding-top: 8px;
            border-top: 1px solid #eee;
        }
        .cart-actions {
            display: flex;
            gap: 10px;
            margin-top: 20px;
        }
        .cart-actions button {
            flex: 1;
            padding: 10px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        .cart-actions .clear-btn {
            background: #dc3545;
            color: white;
        }
        .cart-actions .pay-btn {
            background: #28a745;
            color: white;
        }
        .loading-dots {
            display: inline-block;
        }
        .loading-dots span {
            animation: blink 1.4s infinite both;
            opacity: 0;
        }
        .loading-dots span:nth-child(2) {
            animation-delay: 0.2s;
        }
        .loading-dots span:nth-child(3) {
            animation-delay: 0.4s;
        }
        @keyframes blink {
            0% {
                opacity: 0;
            }
            50% {
                opacity: 1;
            }
            100% {
                opacity: 0;
            }
        }
        .input-container {
            display: flex;
            gap: 10px;
        }
        input[type="text"] {
            flex: 1;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 8px;
            font-size: 14px;
        }
        button {
            padding: 10px 20px;
            background: #007bff;
            color: white;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-size: 14px;
        }
        button:disabled {
            background: #ccc;
            cursor: not-allowed;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>智能点餐助手</h1>
        <div class="chat-container" id="chat-box">
            <div class="message bot-message">您好！我是您的点餐助手，请问您想吃什么？</div>
        </div>
        <div class="input-container">
            <input type="text" id="user-input" placeholder="输入您的需求...">
            <button id="send-btn">发送</button>
        </div>
    </div>
    <!-- 购物车图标 -->
    <div class="cart-icon" id="cart-icon">
        <span class="cart-badge" id="cart-badge">0</span>
        🛒
    </div>

    <!-- 购物车弹窗 -->
    <div class="cart-overlay" id="cart-overlay"></div>
    <div class="cart-modal" id="cart-modal">
        <h3>购物车</h3>
        <div id="cart-items"></div>
        <div class="cart-total" id="cart-total">总价：0元</div>
        <div class="cart-actions">
            <button class="clear-btn" id="clear-cart">清空购物车</button>
            <button class="pay-btn" id="pay-btn">立即支付</button>
        </div>
    </div>

    <script src="/static/dish-config.js"></script>
    <script>
        // 使用外部配置
        const { DISH_MESSAGE, DISH_REGEX } = DISH_CONFIG;

        const chatBox = document.getElementById('chat-box');
        const userInput = document.getElementById('user-input');
        const sendBtn = document.getElementById('send-btn');

        async function sendMessage() {
            const message = userInput.value.trim();
            if (!message) return;

            // 添加用户消息
            const userMessage = document.createElement('div');
            userMessage.className = 'message user-message';
            userMessage.textContent = message;
            chatBox.appendChild(userMessage);

            // 清空输入框
            userInput.value = '';
            sendBtn.disabled = true;

            try {
                // 调用API
                // 创建助手消息容器并显示加载动画
                const botMessage = document.createElement('div');
                botMessage.className = 'message bot-message';
                const loadingDots = document.createElement('div');
                loadingDots.className = 'loading-dots';
                loadingDots.innerHTML = '<span>.</span><span>.</span><span>.</span>';
                botMessage.appendChild(loadingDots);
                chatBox.appendChild(botMessage);

                // 流式处理响应
                console.log("开始调用后端/api/chat接口......");
                const response = await fetch('/api/chat', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        message: message,
                        history: []
                    })
                });

                const reader = response.body.getReader();
                const decoder = new TextDecoder();
                let responseText = '';

                let done = false;
                while (!done) {
                    const { done: chunkDone, value } = await reader.read();
                    done = chunkDone;

                    // 解码并显示响应内容
                    const chunk = decoder.decode(value, { stream: true });
                    try {
                        // 按换行符分割多个JSON对象
                        const jsonObjects = chunk.split('\n');
                        for (const jsonStr of jsonObjects) {
                            const trimmedStr = jsonStr.trim();
                            if (trimmedStr) {
                                try {
                                    const jsonData = JSON.parse(trimmedStr);
                                    if (jsonData.response) {
                                        responseText += jsonData.response;
                                        // 更新流式文字
                                        const textMessage = botMessage.querySelector('#streaming-text') || botMessage;
                                        textMessage.textContent = responseText;
                                        chatBox.scrollTop = chatBox.scrollHeight;
                                        // 立即更新UI
                                        await new Promise(resolve => setTimeout(resolve, 0));
                                    }
                                } catch (e) {
                                    console.error('Error parsing JSON:', e, 'Chunk:', trimmedStr);
                                }
                            }
                        }
                    } catch (e) {
                        console.error('Error parsing JSON:', e, 'Chunk:', chunk);
                    }
                }

                // 流式响应完成后添加菜品卡片
                const dishes = [...new Set(responseText.match(DISH_REGEX) || [])];
                if (dishes.length > 0 && !botMessage.querySelector('.dish-cards-container')) {
                    const cardsContainer = document.createElement('div');
                    cardsContainer.className = 'dish-cards-container';
                    dishes.forEach(dish => {
                        const card = document.createElement('div');
                        card.className = 'dish-card';
                        card.innerHTML = `
                            <img src="/dish/${dish}.jpg" alt="${dish}" class="dish-image">
                            <div class="dish-info">
                                <div class="dish-name">${dish}</div>
                                <div class="dish-price">${DISH_MESSAGE[dish]}元</div>
                                <button class="add-to-cart-btn" data-dish="${dish}" data-price="${DISH_MESSAGE[dish]}">加入购物车</button>
                            </div>
                        `;
                        cardsContainer.appendChild(card);
                    });
                    botMessage.appendChild(cardsContainer);
                }
            } catch (error) {
                console.error('Error:', error);
                const errorMessage = document.createElement('div');
                errorMessage.className = 'message bot-message';
                errorMessage.textContent = '抱歉，出现了一些问题，请稍后再试。';
                chatBox.appendChild(errorMessage);
            } finally {
                sendBtn.disabled = false;
                chatBox.scrollTop = chatBox.scrollHeight;
            }
        }

        // 购物车数据
        let cart = [];
        const cartIcon = document.getElementById('cart-icon');
        const cartBadge = document.getElementById('cart-badge');

        // 更新购物车图标
        function updateCartBadge() {
            const totalItems = cart.reduce((sum, item) => sum + item.quantity, 0);
            cartBadge.textContent = totalItems;
            cartBadge.style.display = totalItems > 0 ? 'block' : 'none';
        }

        // 添加菜品到购物车
        function addToCart(dish, price) {
            const existingItem = cart.find(item => item.dish === dish);
            if (existingItem) {
                existingItem.quantity += 1;
            } else {
                cart.push({
                    dish: dish,
                    price: price,
                    quantity: 1
                });
            }
            updateCartBadge();
        }

        // 显示购物车内容
        function showCart() {
            const cartModal = document.getElementById('cart-modal');
            const cartOverlay = document.getElementById('cart-overlay');
            const cartItems = document.getElementById('cart-items');
            const cartTotal = document.getElementById('cart-total');

            // 更新购物车内容
            cartItems.innerHTML = cart.map(item => `
                <div class="cart-item">
                    <span>${item.dish}</span>
                    <div class="quantity-control">
                        <button class="quantity-btn" onclick="updateQuantity('${item.dish}', -1)">-</button>
                        <span class="quantity">${item.quantity}</span>
                        <button class="quantity-btn" onclick="updateQuantity('${item.dish}', 1)">+</button>
                    </div>
                    <span>${item.price * item.quantity}元</span>
                </div>
            `).join('');

            // 更新总价
            const total = cart.reduce((sum, item) => sum + item.price * item.quantity, 0);
            cartTotal.textContent = `总价：${total}元`;

            // 显示弹窗
            cartModal.classList.add('open');
            cartOverlay.classList.add('open');
        }

        // 关闭购物车弹窗
        function closeCart() {
            const cartModal = document.getElementById('cart-modal');
            const cartOverlay = document.getElementById('cart-overlay');
            cartModal.classList.remove('open');
            cartOverlay.classList.remove('open');
        }

        // 清空购物车
        function clearCart() {
            cart = [];
            updateCartBadge();
            closeCart();
        }

        // 初始化购物车事件
        function initCart() {
            const cartOverlay = document.getElementById('cart-overlay');
            const clearBtn = document.getElementById('clear-cart');
            const payBtn = document.getElementById('pay-btn');

            // 点击遮罩层关闭弹窗
            cartOverlay.addEventListener('click', closeCart);

            // 清空购物车
            clearBtn.addEventListener('click', clearCart);

            // 支付按钮
            payBtn.addEventListener('click', () => {
                if (cart.length === 0) {
                    alert('您的购物车是空的');
                    return;
                }
                alert('支付功能正在开发中，敬请期待！');
                closeCart();
            });
        }

        // 更新菜品数量
        function updateQuantity(dish, delta) {
            const item = cart.find(i => i.dish === dish);
            if (item) {
                item.quantity += delta;
                if (item.quantity <= 0) {
                    cart = cart.filter(i => i.dish !== dish);
                }
                updateCartBadge();
                showCart(); // 刷新购物车显示
            }
        }

        // 初始化
        initCart();

        // 事件监听
        sendBtn.addEventListener('click', sendMessage);
        userInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                sendMessage();
            }
        });

        // 购物车点击事件
        cartIcon.addEventListener('click', showCart);

        // 加入购物车按钮事件
        document.addEventListener('click', (e) => {
            if (e.target.classList.contains('add-to-cart-btn')) {
                const dish = e.target.dataset.dish;
                const price = parseFloat(e.target.dataset.price);
                addToCart(dish, price);
                alert(`已添加 ${dish} 到购物车`);
            }
        });
    </script>
</body>
</html>
